package com.zmn.oms.api.controller.third.common;

import com.alibaba.fastjson.JSONObject;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.api.listener.OrderChangeNotifyFactory;
import com.zmn.oms.business.interfaces.third.SyncOrderStatusService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.model.entity.third.SyncOrderStatus;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.zmn.business.interfaces.open.OrderChangeNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 类描述：给第三方同步工单状态
 *
 * @author wangxiaokun
 * @since 2020/7/30 21:38
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class SyncOrderStatusController {

    @Autowired
    private SyncOrderStatusService syncOrderStatusService;

    @GetMapping("/syncOrderStatus")
    public String syncOrderStatus(String sign){
        if ("zmnTest666666".equals(sign)){

            log.info("【向第三方推送订单状态】开始查询...");

            //查询数据库需要推送的订单
            List<SyncOrderStatus> list = syncOrderStatusService.listSyncOrder();
            if (CollectionUtil.isNullOrEmpty(list)){
                return "【向第三方推送订单状态】没有找到订单";
            }

            //成功推送的数量
            AtomicInteger success = new AtomicInteger();
            //失败推送的数量
            AtomicInteger error = new AtomicInteger();
            //每个订单错误内容
            Map<Long, String> map = new HashMap<>();

            list.forEach(order -> {

                try {
                    OrderWorkLogChange orderWorkLogChange = null;
                    //如果有扩展数据直接转换
                    if (StringUtil.isNotBlank(order.getSyncField())) {
                        orderWorkLogChange = JSONObject.parseObject(order.getSyncField(), OrderWorkLogChange.class);
                    } else {
                        orderWorkLogChange = new OrderWorkLogChange();
                    }

                    if (Objects.isNull(orderWorkLogChange)) {
                        map.put(order.getWorkId(), "【向第三方推送订单状态】扩展信息不正确，请重新检查。");
                    }

                    //订单id，工单id，渠道id，订单日志类型，外部工单号
                    orderWorkLogChange.setOrderId(order.getWorkId());
                    orderWorkLogChange.setWorkId(order.getWorkId());
                    orderWorkLogChange.setChannelId(order.getChannelId());
                    orderWorkLogChange.setLogType(order.getLogType());
                    orderWorkLogChange.setInputType(OrderConsts.ORDER_INPUT_TYPE_API);
                    orderWorkLogChange.setOuterId(order.getOuterId());

                    OrderChangeNotifyService orderChangeNotifyService = OrderChangeNotifyFactory.getInstance(
                            orderWorkLogChange);
                    if (orderChangeNotifyService != null) {
                        orderChangeNotifyService.notifyChange(orderWorkLogChange);
                        //成功直接修改同步状态，全部成功后自己手动删除表数据
                        order.setResult("成功");
                        order.setSyncStatus(1);
                        syncOrderStatusService.updateSyncOrderStatusByWorkId(order);
                        success.getAndIncrement();
                    } else {
                        map.put(order.getWorkId(), "【向第三方推送订单状态】没找到渠道对应的同步器：channelId=" +
                                order.getChannelId());
                        error.getAndIncrement();
                    }

                } catch (Exception e) {
                    error.getAndIncrement();
                    map.put(order.getWorkId(), "同步失败！异常消息：" + e.getMessage());
                    order.setResult("失败");
                    order.setSyncStatus(1);
                    syncOrderStatusService.updateSyncOrderStatusByWorkId(order);
                }

                log.info("【向第三方推送订单状态】成功次数：" + success + "，失败次数：" + error);
            });
            return "成功：" + success + "，失败：" + error + "，失败内容：" + JSONObject.toJSONString(map);
        }
        return "hello world";
    }
}
